import uuid
import hashlib
import time
import random
import requests


# 生成nonce
def gen_nonce_new(i2):
    stringBuffer = ""
    for i3 in range(i2):
        stringBuffer += "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"[random.randint(0, 61)]
    return stringBuffer


# 生成sign值
def gen_sign(info, url_data):
    # 因为java有排序 在python中需要sorted来调整,sorted是根据acill码点进行排序
    result = "&".join([f"{key}={info[key]}" for key in sorted(info.keys())])
    # print("这是经过排序后的格式:", result)

    # 加密前的明文
    str_sign = url_data + result + 'aA4@ud^926U(}^r9'
    # print("这是加密前的明文:", str_sign)

    obj = hashlib.md5()
    byte = obj.update(str_sign.encode('utf-8'))
    hex_string = obj.hexdigest()

    # 对二进制进行hash
    hash_bytes = obj.digest()

    # 将字节字符串转换为字符数组
    hash_array = list(hash_bytes)

    a = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]

    def b(byte):
        i2 = int(byte) // 16
        # print(i2)
        sb = ''
        strArr = a
        sb += strArr[i2]
        sb += strArr[byte % 16]
        return sb

    def c(bArr):
        stringBuffer = ""
        for byte in bArr:
            stringBuffer += b(byte)
        return stringBuffer

    # sign值：
    g_sign = c(hash_array)
    return g_sign


# 获取UUID
x_device_udid = uuid.uuid4()
x_device_uuid = str(x_device_udid).replace("-", "")

# 生成/nodes/5666的nonce
nodes_nonce = gen_nonce_new(16)

# 获取nodes_time的时间戳
nodes_time = str(int(time.time()))

# nodes_info的
nodes_info = {
    "last_items_count": 0,
    "nonce": nodes_nonce,
    "timestamp": nodes_time,
}

# url要参与sign的生成
url_data = f'https://api2.tophub.app/nodes/167'

# 获取nodes_sign签名
nodes_sign = gen_sign(nodes_info, url_data)

# 构造请求头
headers = {
    "authorization": "7761d7f192092ff72f8824b2d9071a60",    # 可不带
    "accept": "application/vnd.tophub.v1+json",
    "user-agent": "TophubApp/1.0 Mozilla/5.0 (Linux; Android 11; Pixel 2 XL Build/RP1A.201005.004.A1; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/118.0.0.0 Mobile Safari/537.36",
    "x-network-type": "NETWORK_WIFI",
    "x-app-version": "18",
    "x-app-package-name": "today.tophub.app",
    "x-app-version-name": "1.9.3",
    "x-device-uuid": x_device_uuid,
    "x-device-model": "Pixel2XL",
    "x-device-udid": str(x_device_udid),
    "accept-encoding": "gzip"
}

# 请求参数
params = {
    "last_items_count": 0,
    "nonce": nodes_nonce,
    "sign": nodes_sign,
    "timestamp": nodes_time
}

# 自行拼接
url = url_data + '?' + '&'.join([f'{key}={value}' for key, value in params.items()])
print(f'**********正在访问 {url} 页面**********\n')
res = requests.get(url=url, headers=headers)
print(res.json())
